package com.wanghlme.day29.Controller;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.DOMReader;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;

public class DomForJavaParse {
//    private static String xmlPath = "structs.xml";

    public static String parseXmlByDom(String xmlPath) {
        String path = null;
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = null;
        try {
            builder = factory.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }
        InputStream inStream = DomForJavaParse.class.getClassLoader().getResourceAsStream(xmlPath);
        org.w3c.dom.Document document = null;
        try {
            assert builder != null;
            document = builder.parse(inStream);
        } catch (SAXException | IOException e) {
            e.printStackTrace();
        }
        DOMReader domReader = new DOMReader();
        Document doc = domReader.read(document);
        Element element = doc.getRootElement();
        Iterator<Element> it = element.elementIterator();
        while (it.hasNext()) {
            path = it.next().attributeValue("back-package");
        }
        return path;
    }
}
